package com.weiiew.backend.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author 魏锴
 * @since 2025/6/6
 */
@Slf4j
@Configuration
public class ShutdownKeyConfig {

    // 存储密钥的引用
    private final AtomicReference<String> shutdownKey = new AtomicReference<>(null);

    /**
     * 从启动参数中提取密钥
     */
    @EventListener(ApplicationReadyEvent.class)
    public void captureShutdownKey(ApplicationReadyEvent event) {
        String key = event.getApplicationContext()
                .getEnvironment()
                .getProperty("shutdown.key");

        if (key != null && !key.isEmpty()) {
            shutdownKey.set(key);
            log.info("Shutdown key initialized: " + key);
        } else {
            log.warn("No shutdown key provided! Add --shutdown.key=your_secret to startup command");
        }
    }

    /**
     * 提供密钥访问的Bean
     */
    @Bean
    public AtomicReference<String> shutdownKeyHolder() {
        return shutdownKey;
    }
}